<template>
  <el-tabs type="border-card">
    <el-tab-pane style="position: relative" label="打卡区域设置">
      <div class="topbtn">
        <el-button type="primary" @click="create">新建区域</el-button>
        <el-button type="primary" @click="editClose" v-if="editP"
          >保存编辑</el-button
        >
        <el-button type="primary" @click="playFence">操作预览</el-button>
      </div>
      <div ref="container" style="height: 650px" id="container"></div>
    </el-tab-pane>
    <!-- 区域填写-->
    <el-dialog
      class="buildDia"
      width="20%"
      title="请选择区域"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="buildForm">
        <el-form-item>
          <el-select
            class="buildSelect"
            v-model="buildForm.build"
            clearable
            filterable
            placeholder="请选择指定区域"
          >
            <el-option
              v-for="item in buildList"
              :key="item.number"
              :label="item.name"
              :value="item.number"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRange()">取 消</el-button>
        <el-button type="primary" @click="submitRange()">确 定</el-button>
      </div>
    </el-dialog>

    <!--播放器-->
    <div class="video_con" v-show="videoShow" style="display: none">
      <video
        id="myVideo"
        controls="controls"
        src="@/assets/media/fence.mp4"
      ></video>
      <div class="mask" @click="hideVedio"></div>
    </div>

    <!-- 时间分页 -->
    <el-tab-pane
      label="打卡时间设置"
      :data="dataList"
      v-loading="dataListLoading"
    >
      <div class="block">
        <el-form ref label-width="180px" :data="dataList">
          <!-- v-loading="dataListLoading" -->
          <el-form-item label="总辅导员导入截止时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                prop="counsellorImportDeadline"
                v-model="form.counsellorImportDeadline"
                format="HH:mm"
                :picker-options="{
                  selectableRange: '8:00:00 - 18:00:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="打卡起始时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                prop="punchStartTime"
                v-model="form.punchStartTime"
                format="HH:mm"
                :picker-options="{
                  selectableRange: '20:00:00 - 22:00:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="打卡终止时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="form.punchEndTime"
                format="HH:mm"
                prop="punchEndTime"
                :picker-options="{
                  selectableRange: '21:40:00 - 22:30:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="寝室关门时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="form.closeDoorTime"
                format="HH:mm"
                prop="closeDoorTime"
                :picker-options="{
                  selectableRange: '20:00:00 - 22:30:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="学生抽查开始时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="form.studentCheckStartTime"
                format="HH:mm"
                prop="studentCheckStartTime"
                :picker-options="{
                  selectableRange: '21:40:00 - 22:30:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="学生抽查结束时间">
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="form.studentCheckEndTime"
                format="HH:mm"
                prop="studentCheckEndTime"
                :picker-options="{
                  selectableRange: '22:00:00 - 22:30:00',
                }"
                placeholder="选择时间"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <!--  -->
          <el-form-item style="margin-left: 55px; margin-right: 60px">
            <el-button
              size="small"
              type="primary"
              v-show="commitType"
              @click="addConfig"
              >提 交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { useMapApi } from '@/utils/useMapApi'
import {
  getRangeList,
  setRange,
  updataRange,
  getConfig,
  getNoFenceBuildList,
  getBuildingList,
  addConfigDetails,
  updataDate,
} from '@/api/src/range'
import '@amap/amap-jsapi-types'

function initPolyon(data, map, that, cb) {
  return data.map((ele) => {
    const polygon = new AMap.Polygon({
      path: ele.points,
      fillOpacity: 0.4,
      fillColor: '#1791fc',
      zIndex: 50,
    })
    let temp
    // 列表为空不设置标签
    if (ele.points.length != 0) {
      temp = new AMap.Text({
        text: ele.title,
        map,
        position: ele.points[0],
      })
    }

    polygon.id = ele.id

    map.add(polygon)

    var contextMenu = new AMap.ContextMenu()
    contextMenu.addItem(
      '编辑',
      () => {
        const polyEditor = new AMap.PolyEditor(map, polygon)
        polyEditor.open()
        that.editP = true
        that.polyEditor = polyEditor
        polyEditor.on('end', async (event) => {
          const data = {
            buildNumber: event.target.id,
            lals: event.target.getPath().map((ele) => [ele.lng, ele.lat]),
          }
          const { message } = await updataRange(data)
          that.$message({
            type: 'success',
            message,
          })
          that.editP = false
        })
      },
      0
    )
    contextMenu.addItem(
      '删除',
      () => {
        console.log(polygon)
        that
          .$confirm('此操作将删除该区域, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(async () => {
            map.remove(polygon)
            map.remove(temp)
            const data = {
              buildNumber: polygon.id,
              lals: [],
            }
            const { message } = await updataRange(data)
            that.$message({
              type: 'success',
              message: message,
            })
            that.getBuildings()
          })
          .catch(() => {
            that.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      1
    )

    polygon.on('rightclick', function (e) {
      contextMenu.open(map, e.lnglat)
    })

    return {
      polygon,
      id: ele.id,
    }
  })
}

export default {
  created() {
    this.getDataList()
  },
  methods: {
    create() {
      // 在地图中添加MouseTool插件
      const mouseTool = new AMap.MouseTool(this.map)
      this.mouseTool = mouseTool
      mouseTool.polygon()

      //用鼠标工具画多边形
      const overlays = []

      mouseTool.on('draw', (type, obj) => {
        var polygonItem = type.obj
        var path = polygonItem.getPath() //取得绘制的多边形的每一个点坐标
        const mapPath = path.map(({ lat, lng }) => {
          return [lng, lat]
        })

        mouseTool.close()
        // 点坐标赋值
        this.eiditPoints = mapPath
        // 区域弹窗
        this.dialogFormVisible = true
      })
    },
    editClose() {
      this.polyEditor.close()
    },

    // 打开播放器
    playFence() {
      this.videoShow = true
    },
    hideVedio() {
      this.videoShow = false
      var myVideo = document.getElementById('myVideo')
      myVideo.pause()
    },
    // 楼栋下拉
    async getBuildings() {
      const data = await getNoFenceBuildList()
      this.buildList = data
    },

    // 取消新建
    cancelRange() {
      this.mouseTool.close(true)
      this.dialogFormVisible = false
      this.buildForm.build = ''
    },

    // 新建提交
    async submitRange() {
      this.dialogFormVisible = false
      const buildNumber = this.buildForm.build
      const data = {
        buildNumber: buildNumber,
        lals: this.eiditPoints,
      }
      // 获取楼栋名
      const builds = await getNoFenceBuildList(buildNumber)
      const buildName = builds[0].name
      const { message } = await updataRange(data)

      new AMap.Text({
        text: buildName + '打卡区域',
        map: this.map,
        position: this.eiditPoints[0],
      })
      this.$message({
        type: 'success',
        message,
      })
      this.buildForm.build = ''
      this.getBuildings()
    },
    // 获取时间
    async getDataList() {
      this.dataListLoading = true
      this.dataList = []

      const { data } = await getConfig()
      Object.keys(data).forEach((ele) => {
        const start = data[ele].split(':')[0]
        const end = data[ele].split(':')[1]
        this.form[ele] = new Date(2016, 9, 10, start, end)
      })
    },

    // 取消
    cancelForm() {
      this.drawer = false
    },

    async addConfig() {
      this.$confirm('此操作将永久修改该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const newSelectTime = []
          Object.keys(this.form).forEach((ele, index) => {
            newSelectTime.push({
              name: ele,
              value: `${this.form[ele].getHours()}:${this.form[
                ele
              ].getMinutes()}`,
            })
          })
          console.log(newSelectTime)
          const { data } = await updataDate(newSelectTime)
          console.log(data)
          console.log(this.form)
          this.$message({
            type: 'success',
            message: '修改成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改',
          })
        })
    },
    //
  },
  async mounted() {
    this.getBuildings()
    await useMapApi()

    const wrapper = this.$refs.container
    const map = new AMap.Map(wrapper, {
      center: [119.636347, 29.062488],
      zoom: 16, //级别
    })
    this.map = map

    const { data } = await getRangeList()

    const res = initPolyon(data, map, this)
    console.log(res)
  },
  data() {
    return {
      // 区域输入弹窗
      dialogFormVisible: false,
      buildForm: {
        build: '',
      },
      buildList: [],
      eidtPoints: [],
      editP: '',
      form: {
        counsellorImportDeadline: '',
        punchStartTime: '',
        punchEndTime: '',
        closeDoorTime: '',
        studentCheckStartTime: '',
        studentCheckEndTime: '',
      },
      drawer: false,
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      dynamicTags: [],
      commitType: true,
      id: '',
      videoShow: false,
    }
  },
}
</script>

<style>
.el-range-editor .el-range-input {
  margin-left: 10px;
  line-height: 1;
}

.topbtn {
  position: absolute;
  z-index: 100;
  right: 0px;
  padding: 20px;
}

.amap-overlay-text-container {
  padding: 10px;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border: 1px solid;
  background-color: red;
  border-radius: 20px;
  transform: scale(0.5) translateX(-50px);
}

.video_con video {
  position: fixed;
  width: 1000px;
  height: 560px;
  left: 50%;
  top: 50%;
  margin-top: -300px;
  transform: translateX(-50%);
  z-index: 990;
}

.video_con .mask {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 980;
  background-color: rgba(0, 0, 0, 0.8);
}
</style><style lang="less" scoped>
#app {
  height: 800px;
}

// .button {
// background: rgb(255, 255, 255);
// }
</style>
